// Default values
var character         = $('#character');
var speedRun 		      = 7; // ms
var sewerToSewer      = 170; // khoang cach giua 2 ong cong
var playScore 		    = 0;
var highestScore      = 0;
var totalMaps         = 0;
var soundOn           = true;
var newScore          = false;
var isRun 			      = true;
var getReady 		      = true;
var isReset           = false;
var timeoutFlydown;
var timeoutRotateDown;
var intervalMapsUpdate = [];
var intervalMapsRun;
var intervalScore;

$(document).ready(function(){
  $('#overlay').mousedown(function(){ // su kien click chuot
    flyUp();
    if(isReset){
      mapsRun();
      isReset = false;
    }
    getReady = false;
    $('#overlay2.ready').fadeOut();
  });
  
  $('body').keypress(function(){ // su kien bam ban phim
    flyUp();
    if(isReset){
      mapsRun();
      isReset = false;
    }
    getReady = false;
    $('#overlay2.ready').fadeOut();
  });
  
  $('#sounds').click(function(){ // BAT-TAT am thanh
    $('#sounds').toggleClass('mute');
    if( $('#sounds').hasClass('mute') ){
      soundOn = false;
    }else{
      soundOn = true;
    }
  });
  
  preloadSFX();
  mapsRun();
  scrollGround();
  charEffect();
  randomColor();
});

function preloadSFX(){
  var sfxsrc = 'http://template-files.googlecode.com/svn/trunk/flappy-files/sounds/sfx_';
  
  $('#wrapper').prepend('<audio id="sfx-hit"><source src="'+sfxsrc+'hit'+'.ogg" type="audio/ogg"></audio>');
  $('#wrapper').prepend('<audio id="sfx-point"><source src="'+sfxsrc+'point'+'.ogg" type="audio/ogg"></audio>');
  $('#wrapper').prepend('<audio id="sfx-wing"><source src="'+sfxsrc+'wing'+'.ogg" type="audio/ogg"></audio>');
  $('#wrapper').prepend('<audio id="sfx-tada"><source src="'+sfxsrc+'tada'+'.ogg" type="audio/ogg"></audio>');
  
  return true;
}
function sounds(name){
  var sfxEle = document.getElementById('sfx-'+name);
  if( soundOn ){
    sfxEle.play();
  }
}

function randomColor(){
  var bg = Math.floor((Math.random()*2)+1); // 1 to 2
  var bird = Math.floor((Math.random()*3)+1); // 1 to 3
  
  $('#wrapper').removeClass().addClass('bg'+bg);
  $('#character').removeClass().addClass('bird'+bird);
}

function flyUp(){
  if(isRun){
    var currentOff = character.offset();
    var currentTop = currentOff.top;
    
    charRotate('up');
    clearTimeout(timeoutFlydown);
    sounds('wing');
	
    if(currentTop > 0){ // con trong man hinh #wrapper
      $('#character').stop().animate({
        top: "-=57" // do cao nhay len
      }, 250, function(){
		
		timeoutFlydown = setTimeout(function(){
			flyDown(); // nhay len xong nhay xuong
		}, 70);
		
      }); // end animate
	  
    }else{ // bay qua khoi man hinh #wrapper
        charRotate('down');
		
    } // endif currentTop
  } // endif isRun
}

function flyDown(){
  var currentOff = character.offset();
  var currentTop = currentOff.top;
  var wrapHeight = $('#wrapper').height();
  
  var qd = wrapHeight - currentTop;
  var vt = 1;
  var tg = qd / vt;
  var times = tg + 500;
  var charTopInBottom = (wrapHeight - character.height()) - $('#ground').height();
  
  $('#character').stop().animate({
	top: charTopInBottom
  }, times, function(){
	gameOver();
  });
  
  timeoutRotateDown = setTimeout(function(){
	charRotate('down');
  }, 165);
}

function charEffect(){
  var charAction = 0;
  var charAction2 = 0;
  var charH = $('#character').height();
  
  setInterval(function(){
    if(isRun){
      charAction++;
      charAction2 = charAction - 1;
      
      if(charAction > 3) charAction = 1;
      if(charAction2 < 1) charAction2 = 3;
      
      $('#character').addClass('act'+charAction).removeClass('act'+charAction2);
	  
	  if(getReady){
		$('#character').height(charH+2);
	  }else{
		$('#character').height(charH);
	  }
    } // endif isRun
  }, 125);
}

function charRotate(rotate){
  if(rotate == 'up'){
	clearTimeout(timeoutRotateDown);
    $('#character').removeClass('down').addClass('up');
  }
  if(rotate == 'down'){
    $('#character').removeClass('up').addClass('down');
  }
}

function mapsRun(){ // Start Run
  var i      = 0;
  var mapsID = 0;
  
	intervalMapsRun = setInterval(function(){
		if( getReady ){
			i = 0;
			mapsID = 0;
		}else{
			i++;
			
			if(i == sewerToSewer){
				i = 0;
				if( isRun ){
					mapsID++; // ID ong cong
					mapsRandom(mapsID); // them ong cong
          totalMaps = mapsID;
					mapsUpdate(mapsID);
				}
			}
		}
	}, speedRun);
}

function mapsUpdate(mapsID){
	var firstMapsX = 350; // toa do X ban dau cua ong cong

	intervalMapsUpdate[mapsID] = setInterval(function(){ // ong cong chay qua trai
		
		if(isRun){
			$('#maps'+mapsID).css('left', firstMapsX);
			firstMapsX--;
			
			if(firstMapsX < 109 && firstMapsX > 31){ // bat dau xu ly va cham
				if(collision(mapsID)){
					gameOver();
				}
			}

			if(firstMapsX == 80){ // bat dau tinh diem
				checkScore(mapsID);
        sounds('point');
			}

			if(firstMapsX == -70){ // ra khoi man hinh
				mapsRemove(mapsID); // huy bo doi tuong
			}
		}
		
	}, speedRun);

}

function mapsRandom(mapsID){
  var maps2Top     = Math.floor((Math.random()*200)+30); // random
  var sewerTopH    = maps2Top;
  var sewerBottomY = maps2Top + 110;
  var mapsHtml     = '<div id="maps'+mapsID+'" class="maps"><div style="height: '+sewerTopH+'px" class="top"></div><div class="maps2" style="top:'+maps2Top+'px"></div><div style="top: '+sewerBottomY+'px" class="bottom"></div></div>';
  
  $('#wrapper').append(mapsHtml);
}

function mapsRemove(mapsID){
  $('#maps'+mapsID).remove();
}

function collision(mapsID){ // xu ly va cham
  var character = $('#character');
  var map2 = $('#maps'+mapsID+' .maps2');
  
  if (character.offset().top < map2.offset().top){
    return true;
  }
  if((character.offset().top+character.height()) > (map2.offset().top+map2.height())){
    return true;
  }
  
  return false;
}

function checkScore(mapsID){
  if(isRun){
    $('#point').text(mapsID);
    playScore = mapsID;
  }
}

function setCookie(cname,cvalue,exdays){
  var d = new Date();
  d.setTime(d.getTime()+(exdays*24*60*60*1000));
  var expires = "expires="+d.toGMTString();
  document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname){
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++){
    var c = ca[i].trim();
    if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
  return "";
}

function checkCookie(){
  var cScore = getCookie("bestscore"); // cookie score
  
  if (cScore!=""){ // da set cookie
    if(playScore > cScore){
      newScore = true;
      setCookie("bestscore", playScore, 365);
    }else{
      newScore = false;
    }
    
  }else{ // chua set cookie
    setCookie("bestscore", playScore, 365);
    if(playScore > 0){
      newScore = true;
    }
  }
}

function highPoint(){ // set diem cao nhat
  checkCookie();
  highestScore = getCookie("bestscore");
  medals();
  
  $('#scoreboard .bestscore').text(highestScore);
  if(newScore){
    $('#scoreboard .newscore').show();
    //sounds('tada');
  }else{
    $('#scoreboard .newscore').hide();
  }
}

function medals(){
  var score = 0;
  var medalClass = '';
  
  if(highestScore <= 40){
    if(playScore>9 && playScore<20){ // 10 -> 19
      medalClass = 'bronze';
    }
    if(playScore>19 && playScore<30){ // 20 -> 29
      medalClass = 'silver';
    }
    if(playScore>29 && playScore<40){ // 30 -> 39
      medalClass = 'gold';
    }
    if(playScore>=40){ // over 40
      medalClass = 'platinum';
    }
  }else{ // highestScore over 40
    score = highestScore/4;
    
    if(playScore >= score && playScore < score*2){
      medalClass = 'bronze';
    }
    if(playScore >= score*2 && playScore < score*3){
      medalClass = 'silver';
    }
    if(playScore >= score*3 && playScore <= score*4){
      medalClass = 'gold';
    }
    if(playScore > score*4){
      medalClass = 'platinum';
    }
  }
  
  $('#scoreboard .medal').addClass(medalClass);
}

function scrollGround(){ // cuon nen
  var groundX = 0;
  
  setInterval(function(){
    if(isRun){
      groundX--;
      $('#ground').css('background-position', ''+groundX+'px top');
    }
  }, speedRun);
}

function gameOver(){
  if(isRun){
    flyDown();
    runAscendingScore();
    highPoint();
    sounds('hit');
    $('#overlay').css('backgroundColor', '#FFF').fadeOut(); // flash screen
    $('#gameoverTxt, #scoreboard, #playbutton, #rankbutton').addClass('active');
    $('#point').hide();
    clearInterval(intervalMapsRun);
    
    for(i=0; i<=totalMaps; i++){
      clearInterval(intervalMapsUpdate[i]);
    }
    
    isRun=false;
  }
}

function runAscendingScore(){
  var score = 0;
  var delayScore = 400;
  var msScore = 500/playScore;
  var scoreEle = $('#scoreboard .score');
  
  setTimeout(function(){
    ascendingScore = setInterval(function(){
      if(playScore < 500){
        if(score < playScore){
          score++;
          scoreEle.text(score);
          if(score == playScore){ // chay xong clearInterval
            clearInterval(ascendingScore);
          }
        }else if(playScore == 0){
          scoreEle.text(0);
          clearInterval(ascendingScore); // chay xong clearInterval
        }

      }else{ // over 500
        if(score < playScore){
          score++;
          if(score == playScore){ // chay xong clearInterval
            clearInterval(ascendingScore);
          }
          scoreEle.text(score);
          setTimeout(function(){
            scoreEle.text(playScore);
            clearInterval(ascendingScore); // chay xong clearInterval
          }, 3000);
        }else{
          score++;
          scoreEle.text(score);
          if(score == playScore){ // chay xong clearInterval
            clearInterval(ascendingScore);
          }
        }
      }
    }, msScore);
  }, delayScore);
}

function resetGame(){
  if(!isRun){
    clearTimeout(timeoutFlydown);
    clearTimeout(timeoutRotateDown);

    $('#point').text('0').show();
    $('#gameoverTxt, #scoreboard, #playbutton, #rankbutton').removeClass('active');
    
    $('#wrapper').append('<div id="blackscreen" style="font-family: Helvetica; font-size: 13px; text-align: center; width: 100%; height: 100%; line-height: 500px; background: #000; color: #FFF; padding: 2px; position: absolute; left: 0; top: 0; z-index: 10000">Loading...</div>').after(function(){
      $('#blackscreen').delay(400).fadeOut(400);
      setTimeout(function(){
        $('#blackscreen').remove();
        $('#overlay').removeAttr('style').show();
      }, 1000);
    });
    
    $('#overlay2.ready').show();
    $('#character').removeClass().removeAttr('style');
    $('#wrapper .maps').remove();
    randomColor();

    playScore   = 0;
    isRun       = true;
    getReady    = true;
    isReset     = true;
  }
}
